<?php
/**
 * @user: thanatos <thanatos915@163.com>
 */

namespace frontend\models;


use common\models\Awards;
use common\models\Record;
use yii\base\Model;

class AwardsForm extends Model
{

    public $name;
    public $tel;
    public $num;

    public function rules()
    {
        return [
            [['name', 'tel', 'num'], 'required'],
        ];
    }

    public function submit($params)
    {
        $this->load($params, '');
        if (!$this->validate()) {
            return false;
        }

        if (Record::find()->count() >= 3000) {
            $this->addError('', '奖品已抽完，活动结束');
            return false;
        }

        // 抽奖
        $result = $this->doAward();
        $model = new Record();
        $model->name = $this->name;
        $model->mobile = $this->tel;
        $model->number = $this->num;
        $model->awards_id = $result->id;
        $user = \Yii::$app->controller->wechatUser;
        $model->openid = $user['original']['unionid'] ?: $user['id'];
        $model->created_at = time();
        if (!$model->save()) {
            return false;
        }
        return $model;
    }

    /**
     * @return Awards|\yii\db\ActiveRecord
     * @author thanatos <thanatos915@163.com>
     */
    public function doAward()
    {
        // 进行抽奖
        $num = rand(1, 100);
        $awards = Awards::find()->all();
        $pro = '';
        foreach ($awards as $k => $award) {
            for ($i = 1; $i <= $award->probability; $i++) {
                $pro[$i] = $k;
            }
        }
        $result = $awards[$pro[$num]];
        // 排除奖品
        if (Record::find()->where(['awards_id' => $result->id])->count() >= $result->num) {
            return $this->doAward();
        }
        return $result;
    }

}